#include "mysqlconn.h"

MysqlConn::MysqlConn()
{
    m_conn = mysql_init(NULL);
    mysql_set_character_set(m_conn, "utf8");
}

MysqlConn::~MysqlConn()
{
    if (m_conn != nullptr)
        mysql_close(m_conn);
    freeRes();
}

bool MysqlConn::connect(const char *user, const char *password, const char *dbname, const char *ip, const unsigned short &port)
{
    if (mysql_real_connect(m_conn, ip, user, password, dbname, port, nullptr, 0) == nullptr)
        return false;
    return true;
}

bool MysqlConn::update(const char *sql)
{
    if (mysql_query(m_conn, sql))
        return false;
    return true;
}

bool MysqlConn::query(const char *sql)
{
    freeRes();
    if (mysql_query(m_conn, sql))
        return false;
    m_res = mysql_store_result(m_conn);
    return true;
}

bool MysqlConn::next()
{
    if (m_res != nullptr)
    {
        m_row = mysql_fetch_row(m_res);
        if (m_row != nullptr)
            return true;
    }
    return false;
}

std::string MysqlConn::value(const unsigned int &index)
{
    int colums = mysql_num_fields(m_res);
    if (index >= colums || index < 0)
        return std::string();
    char *val = m_row[index];
    const unsigned long length = mysql_fetch_lengths(m_res)[index];
    return std::string(val, length);
}

const char *MysqlConn::getError()
{
    return mysql_error(m_conn);
}

// 事务操作
bool MysqlConn::transaction()
{
    return mysql_autocommit(m_conn, false);
}

// 提交事务
bool MysqlConn::commit()
{
    return mysql_commit(m_conn);
}

// 事务回滚
bool MysqlConn::rollBack()
{
    return mysql_rollback(m_conn);
}

void MysqlConn::freeRes()
{
    if (m_res != nullptr)
    {
        mysql_free_result(m_res);
        m_res = nullptr;
    }
}